package com.sphere.freereader.ui;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * Created by songbangbang on 16-8-17.
 */
public class ReaderViewPager extends ViewPager {


    private int mScreenWidth;
    private int mScreenHeight;

    private Context mContext;

    public ReaderViewPager(Context context) {
        super(context);
        init(context);
    }

    public ReaderViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        mContext = context;
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        mScreenWidth  = metrics.widthPixels;
        mScreenHeight = metrics.heightPixels;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev);
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        int action = ev.getAction();
        int x = (int) ev.getX();
        int y = (int) ev.getY();
        switch (action) {
            case MotionEvent.ACTION_DOWN:

                break;

            case MotionEvent.ACTION_UP:
                boolean showMenu = touchInShowMenuArea(x, y);
                if(showMenu)
                    Toast.makeText(mContext, "show menu" + ",x="+x+",y="+y, Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

        return super.onTouchEvent(ev);
    }


    /**
     * 触摸区域是触发菜单显示的区域
     * 1/3 mWidth ~ 2/3 mWidth
     * 1/3 mWidth ~ mHeight-1/3 mWidth
     * @param x
     * @param y
     * @return
     */
    private boolean touchInShowMenuArea(int x, int y) {
        boolean xInArea = x > mScreenWidth / 3 && x < mScreenWidth * 2 / 3;
        boolean yInArea = y > mScreenWidth / 3 && y < mScreenHeight - mScreenWidth / 3;
        return xInArea && yInArea;
    }

    // 触发前一页
    private boolean touchPrevious(int x) {
        return x > 0 && x < mScreenWidth * 1 / 3;
    }

    // 触发下一页
    private boolean touchNext(int x, int y) {
        return !touchInShowMenuArea(x,y) && x > mScreenWidth * 1 / 3 && x < mScreenWidth;
    }
}
